package com.duojuhe.coremodule.form.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.duojuhe.common.annotation.KeyLock;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.encryption.md5.MD5Util;
import com.duojuhe.common.utils.jsonutils.JsonUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.common.utils.sort.SortUtils;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.form.entity.FormProject;
import com.duojuhe.coremodule.form.entity.FormProjectItem;
import com.duojuhe.coremodule.form.entity.FormProjectLogic;
import com.duojuhe.coremodule.form.mapper.FormProjectItemMapper;
import com.duojuhe.coremodule.form.mapper.FormProjectLogicMapper;
import com.duojuhe.coremodule.form.mapper.FormProjectMapper;
import com.duojuhe.coremodule.form.pojo.project.FormProjectIdReq;
import com.duojuhe.coremodule.form.pojo.project.QueryFormProjectRes;
import com.duojuhe.coremodule.form.pojo.projectitem.*;
import com.duojuhe.coremodule.form.service.FormProjectItemService;
import com.duojuhe.coremodule.form.utils.handle.HandleFormUtils;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class FormProjectItemServiceImpl extends BaseService implements FormProjectItemService {
    @Resource
    private FormProjectMapper formProjectMapper;
    @Resource
    private FormProjectItemMapper formProjectItemMapper;
    @Resource
    private FormProjectLogicMapper formProjectLogicMapper;


    @Override
    public ServiceResult<PageResult<List<QueryFormProjectItemPageRes>>> queryFormProjectItemPageResList(QueryFormProjectItemPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort asc,updateTime desc, projectId desc");
        List<QueryFormProjectItemPageRes> list = formProjectItemMapper.queryFormProjectItemPageResList(req.getProjectId());
        for (QueryFormProjectItemPageRes res:list){
            HandleFormUtils.setHandleFormProjectItemPageRes(res);
        }
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 根据项目key查询本项目最大的表单id
     * @param req
     * @return
     */
    @KeyLock(lockKeyParts = "projectId")
    @Override
    public ServiceResult<String> queryFormProjectItemMaxFormItemIdByProjectId(FormProjectIdReq req) {
        String projectId = req.getProjectId();
        QueryFormProjectRes res = formProjectMapper.queryFormProjectResByProjectId(projectId);
        if (res == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        return ServiceResult.ok(res.getMaxFormItemId());
    }

    /**
     * 根据项目Id查询表单项目的表头信息
     * @param req
     * @return
     */
    @Override
    public ServiceResult<List<QueryFormProjectItemTableHeadRes>> queryFormProjectItemTableHeadResByProjectId(FormProjectIdReq req) {
        PageHelperUtil.defaultOrderBy("sort asc,updateTime desc, itemId desc");
        List<QueryFormProjectItemTableHeadRes> list = formProjectItemMapper.queryFormProjectItemTableHeadResByProjectId(req.getProjectId());
        for (QueryFormProjectItemTableHeadRes res:list){
            HandleFormUtils.setHandleFormProjectItemPageRes(res);
        }
        return ServiceResult.ok(list);
    }


    /**
     * 【保存和修改】保存和修改表单项目
     * @param req
     * @return
     */
    @KeyLock(lockKeyParts = "projectId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult saveUpdateFormProjectItem(SaveFormProjectItemReq req) {
        //项目id
        String projectId = req.getProjectId();
        FormProject formProjectOld = formProjectMapper.selectByPrimaryKey(projectId);
        if (formProjectOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        long maxFormItemId = formProjectOld.getMaxFormItemId();
        //排序
        long sort;
        //当前时间
        Date nowDate = new Date();
        //是
        Integer YES = SystemEnum.IS_YES.YES.getKey();
        //否
        Integer NO = SystemEnum.IS_YES.NO.getKey();
        //表单id
        String formItemId = req.getFormItemId();
        //itemId 是有项目id表单id md5组成
        String itemId = MD5Util.getMD532(projectId+formItemId);
        //表单类型
        String type = req.getType();
        FormProjectItem formProjectItemOld = formProjectItemMapper.selectByPrimaryKey(itemId);
        //构建表单子项
        FormProjectItem formProjectItem = HandleFormUtils.buildFormProjectItem(req);
        formProjectItem.setItemId(itemId);
        formProjectItem.setProjectId(projectId);
        formProjectItem.setProjectKey(formProjectOld.getProjectKey());
        formProjectItem.setFormItemId(formItemId);
        formProjectItem.setFormItemType(type);
        formProjectItem.setFormItemLabel(req.getLabel());
        formProjectItem.setFormItemField(req.getFormItemField());
        formProjectItem.setFormItemShowLabel(req.getShowLabel()?YES:NO);
        formProjectItem.setFormItemRequired(req.getRequired()?YES:NO);
        formProjectItem.setFormItemDisplayType(req.getDisplayType()?YES:NO);
        formProjectItem.setFormItemShowRegex(req.getShowRegList()?YES:NO);
        formProjectItem.setFormItemPlaceholder(req.getPlaceholder());
        formProjectItem.setUpdateTime(nowDate);
        formProjectItem.setFormItemSpan(req.getSpan());
        formProjectItem.setFormItemConfig(JsonUtils.objToJson(req.getItemConfig()));
        if (formProjectItemOld==null){
            //获取排序
            sort = formProjectOld.getMaxFormItemSort()+ SortUtils.SORT_DEFAULT_INCR_FACT;
            //表单最大值
            maxFormItemId = formProjectOld.getMaxFormItemId()+1;
           //新增
            formProjectItem.setCreateTime(nowDate);
            formProjectItem.setSort(sort);
            formProjectItemMapper.insertSelective(formProjectItem);
            //更新项目的最大表单id值
            FormProject updateFormProject = new FormProject();
            updateFormProject.setProjectId(projectId);
            updateFormProject.setMaxFormItemId(maxFormItemId);
            updateFormProject.setMaxFormItemSort(sort);
            formProjectMapper.updateByPrimaryKeySelective(updateFormProject);
        }else {
            //获取排序
            sort = formProjectItemOld.getSort();
            //更新
            formProjectItemMapper.updateByPrimaryKeySelective(formProjectItem);
        }
        MaxFormItemIdAndSortRes res = new MaxFormItemIdAndSortRes(maxFormItemId,sort);
        return ServiceResult.ok(res);
    }


    /**
     * 【删除】删除表单项目
     * @param req
     * @return
     */
    @KeyLock(lockKeyParts = "projectId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult deleteFormProjectItem(DeleteFormProjectItemReq req) {
        //项目id
        String projectId = req.getProjectId();
        //表单id
        String formItemId = req.getFormItemId();
        //itemId 是有项目id表单id md5组成
        String itemId = MD5Util.getMD532(projectId+formItemId);
        //删除表单项目
        formProjectItemMapper.deleteByPrimaryKey(itemId);
        //删除项目逻辑记录
        FormProjectLogic deleteFormProjectLogic = new FormProjectLogic();
        deleteFormProjectLogic.setItemId(itemId);
        formProjectLogicMapper.delete(deleteFormProjectLogic);
        return ServiceResult.ok(ErrorCodes.SUCCESS);
    }

    /**
     * 修改表单项目排序值
     * @param req
     * @return
     */
    @KeyLock(lockKeyParts = "projectId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult updateFormProjectItemSort(UpdateFormProjectItemSortReq req) {
        if (ObjectUtil.isNull(req.getAfterPosition())  && ObjectUtil.isNull(req.getBeforePosition())) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //项目id
        String projectId = req.getProjectId();
        FormProject formProjectOld = formProjectMapper.selectByPrimaryKey(projectId);
        if (formProjectOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //表单id
        String formItemId = req.getFormItemId();
        //itemId 是有项目id表单id md5组成
        String itemId = MD5Util.getMD532(projectId+formItemId);
        FormProjectItem formProjectItem = formProjectItemMapper.selectByPrimaryKey(itemId);
        if (formProjectItem==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //重新获取排序
        Long sort = SortUtils.calcSortPosition(req.getBeforePosition(), req.getAfterPosition());
        FormProjectItem updateFormProjectItem = new FormProjectItem();
        updateFormProjectItem.setItemId(itemId);
        updateFormProjectItem.setSort(sort);
        updateFormProjectItem.setUpdateTime(new Date());
        formProjectItemMapper.updateByPrimaryKeySelective(updateFormProjectItem);
        //更新项目主表最大排序值
        if (formProjectOld.getSort()<sort){
            FormProject updateFormProject = new FormProject();
            updateFormProject.setProjectId(projectId);
            updateFormProject.setMaxFormItemSort(sort);
            formProjectMapper.updateByPrimaryKeySelective(updateFormProject);
        }
        MaxFormItemIdAndSortRes res = new MaxFormItemIdAndSortRes(formProjectOld.getMaxFormItemId(),sort);
        return ServiceResult.ok(res);
    }



}
